package org.example.mq;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.example.model.ProductMessage;
import org.example.service.ProductService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
@RabbitListener(queues = "${mqconfig.stock_release_queue}")
public class ProductStockMQListener {

    @Autowired
    private ProductService productService;

    @RabbitHandler
    public void releaseProductStock(ProductMessage productMessage, Message message, Channel channel) throws IOException {
        log.info("监听到ProductMessage: {}", productMessage);
        long msgTag = message.getMessageProperties().getDeliveryTag();
        // 判断确认消息的结果
        boolean flag = productService.releaseProductStock(productMessage);
        try {
            if (flag) {
                // 确认消息消费成功
                channel.basicAck(msgTag, false);
            } else {
                channel.basicAck(msgTag, true);
                log.info("商品库存释放失败，消息为: {}，重回队列", productMessage);
            }
        } catch (IOException e) {
            log.info("释放商品库存异常: {}，消息为: {}，重回队列", e, productMessage);
            // 重新回队列
            channel.basicReject(msgTag, true);
        }
    }

}
